package com.jckj.core.controller;

import com.jckj.core.entity.SysUser;
import com.jckj.core.security.UsernamePasswordToken;
import com.jckj.core.service.UserService;
import com.jckj.core.util.UserUtils;
import com.jckj.core.validator.groups.LoginCheck;
import com.jckj.core.vos.Result;
import com.jckj.core.vos.SysUserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * LoginController.class
 *
 * @author 刘志远
 * @date 2017-12-18
 */
@Controller
@RequestMapping("/")
public class LoginController{

    private final static Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserService userService;

    @RequestMapping("admin/index")
    public String index(){
        return "index";
    }

    /**
     * 登录
     * @param sysUserVo
     * @param bindingResult
     * @return
     */
    @RequestMapping("doLogin")
    @ResponseBody
    public Result doLogin(@ModelAttribute @Validated(value = LoginCheck.class) SysUserVo sysUserVo, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return Result.invalidParams(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken();
        usernamePasswordToken.setUsername(sysUserVo.getUsername());
        usernamePasswordToken.setPassword(sysUserVo.getPassword().toCharArray());
        try{
            subject.login(usernamePasswordToken);
        }
        catch(Exception ex) {
            return Result.error(ex.getMessage());
        }
        SysUser sysUser = userService.findByLoginUsername(sysUserVo.getUsername());
        UserUtils.setLoginUser(sysUser);
        return Result.ok();
    }

    /**
     * 登录
     * @return
     */
    @RequestMapping("login")
    public String login(){
        return "login";
    }

    /**
     * 登出
     * @return
     */
    @RequestMapping("logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:login";
    }
}
